package ua.mykola.polishnotation;

import java.util.Deque;
import java.util.LinkedList;

import ua.mykola.calc.Calculator;

public class RPN1 implements RPN {
	private Calculator calc = new Calculator();

	public double eval(Deque<Object> input) {
		System.out.println(input);
		Deque<Double> stack = new LinkedList<Double>();
		for (Object next : input) {
			if (isDouble(next)) {
				stack.offer(Double.valueOf(next.toString()));
			} else {
				Character c = (Character) next;
				double op2 = stack.pollLast();
				double op1 = stack.pollLast();
				stack.offer(calc.calculate(c, op1, op2));
			}
		}
		return stack.poll();
	}

	private boolean isDouble(Object object) {
		try {
			Double.valueOf(object.toString());
			return true;
		} catch (NumberFormatException e) {
			return false;
		}
	}

}
